package com.sp.fresh_produce.controller;

import com.google.zxing.WriterException;
import com.sp.fresh_produce.common.GenericReturnApiObject;
import com.sp.fresh_produce.controller.dto.VO.OrderVO;
import com.sp.fresh_produce.controller.dto.req.CreateOrderReq;
import com.sp.fresh_produce.service.OrderService;
import jakarta.servlet.http.HttpSession;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.io.IOException;

@RestController
@RequestMapping("/order")
@Tag(name = "Order", description = "订单管理接口")
public class OrderController extends BaseController {

    @Autowired
    private OrderService orderService;

    /**
     * 创建订单
     */
    @PostMapping("/create")
    @Operation(summary = "创建订单")
    public GenericReturnApiObject createOrder(@RequestBody CreateOrderReq createOrderReq, HttpSession session) {
        Integer userId = getCurrentUser(session).getId();
        String orderNo = orderService.createOrder(userId, createOrderReq);
        return GenericReturnApiObject.success(orderNo);
    }

    /**
     * 订单详情
     */
    @GetMapping("/detail")
    @Operation(summary = "前台订单详情")
    public GenericReturnApiObject detail(@RequestParam String orderNo, HttpSession session) {
        OrderVO orderVO = orderService.detail(orderNo);
        return GenericReturnApiObject.success(orderVO);
    }

    /**
     * 取消订单
     */
    @PostMapping("/cancel")
    @Operation(summary = "取消订单")
    public GenericReturnApiObject cancel(@RequestParam String orderNo, HttpSession session) {
        orderService.cancel(orderNo);
        return GenericReturnApiObject.success(null);
    }

    /**
     * 生成订单二维码
     */
    @GetMapping("/qrcode")
    @Operation(summary = "生成订单二维码")
    public GenericReturnApiObject qrcode(@RequestParam String orderNo) throws IOException, WriterException {
        String qrcode = orderService.qrcode(orderNo);
        return GenericReturnApiObject.success(qrcode);
    }

    /**
     *  支付
     */
    @GetMapping("/pay")
    @Operation(summary = "支付")
    public GenericReturnApiObject pay(@RequestParam String orderNo) {
        orderService.pay(orderNo);
        return GenericReturnApiObject.success(null);
    }
}
